import QtQuick 2.0

Rectangle {
    id: slider
    width: 100
    height: 7

    property int max_value: 100
    property real slider_value: slider_handler_mouse_area.value
    property real percent: 0
    property color color: "#0066cc"

    onPercentChanged: {
        slider_handle.x = percent * slider_handler_mouse_area.slider_length - Math.round(-slider_handle.width / 2 + 3)
    }

//    function set_slider_handle_x(pos) {
//        console.log(slider_length + " " + slider.width + " " + pos)
//        slider_handle.x = slider_length * pos + Math.round(-slider_handle.width / 2 + 3)
//        console.log(slider_length)
//    }

    signal slider_clicked(real value);

    Rectangle {
        id: darker
        height: slider.height
        anchors.left: slider.left
        anchors.right: slider_handle.horizontalCenter
        color: slider.color
        radius: 3
        border.width: 1
        border.color: Qt.darker(color, 1.3)
        opacity: 0.8
    }

    MouseArea {
        id: slider_mouse_area
        anchors.fill: slider
        hoverEnabled: true
        onEntered: slider_handle.visible = true
        onExited: slider_handle.visible = false
        onClicked: {
            slider_handle.x = mouseX - (slider_handle.width / 2) - 3
            slider_clicked(slider_value)
        }
    }

    Image {
        id: slider_handle
        visible: false
        source: "../images/slider_handle.png"
        anchors.verticalCenter: parent.verticalCenter
        x: Math.round(-slider_handle.width / 2 + 3)
        MouseArea {
            id: slider_handler_mouse_area
            anchors.fill: slider_handle
            anchors.margins: -4
            drag.target: parent
            drag.axis: Drag.XAxis
            drag.minimumX: Math.round(-slider_handle.width / 2 + 3)
            drag.maximumX: Math.round(slider.width - slider_handle.width/2 - 3)
            property real value: (slider_handle.x - drag.minimumX) / (drag.maximumX - drag.minimumX)
            property real slider_length: drag.maximumX - drag.minimumX
        }
    }
}
